import {AxdrType} from "../asn1.axdr/AxdrType";
import {ReverseByteArrayInputStream} from "../ReverseByteArrayInputStream";
import {ReverseByteArrayOutputStream} from "../ReverseByteArrayOutputStream";
import {Buffer} from "buffer";
import {AxdrOctetString} from "../asn1.axdr/AxdrOctetString";


export class SymmetrySecurity implements AxdrType{

    dataCode : Buffer | null = null;
    p1 : AxdrOctetString | null = null;
    s1 : AxdrOctetString | null = null;


    set_dataCode(dataCode : Buffer){
        this.dataCode = dataCode;
    }

    set_all(p1 : AxdrOctetString, s1 : AxdrOctetString){
        this.p1 = p1;
        this.s1 = s1;
    }

    setP1(p1 : AxdrOctetString){
        this.p1 = p1;
    }

    setS1(s1 : AxdrOctetString){
        this.s1 = s1;
    }

    decode(input: ReverseByteArrayInputStream): number {
        let codeLength = 0;

        this.p1 = new AxdrOctetString();
        codeLength += this.p1.decode(input);

        this.s1 = new AxdrOctetString();
        codeLength += this.s1.decode(input);

        return codeLength;
    }

    encode(output: ReverseByteArrayOutputStream): number {
        let codeLength;

        if (this.dataCode != null) {
            codeLength = this.dataCode.length;
            for (let i = this.dataCode.length - 1; i >= 0; i--) {
                output.write(this.dataCode[i]);
            }
        } else {
            if(this.p1 != null && this.s1 != null){
                codeLength = 0;
                codeLength += this.s1.encode(output);
                codeLength += this.p1.encode(output);
            }else{
                throw new Error("p1 || s1 is null");
            }
        }
        return codeLength;
    }

    encodeAndSave(encodingSizeGuess: number) {
        let revOStream = new ReverseByteArrayOutputStream();
        revOStream.setBufSize(encodingSizeGuess);
        this.encode(revOStream);
        this.dataCode = revOStream.getArray();
    }

    toString(): string {
        if (this.p1 != null && this.s1 != null) {
            return "sequence: {" + "p1: " + this.p1 + ", s1: " + this.s1 + "}";
        } else {
            return "p1 || s1 is null";
        }
    }

}
